/*
 * This file is part of PGNParse.
 *
 * PGNParse is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * PGNParse is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PGNParse.  If not, see <http://www.gnu.org/licenses/>. 
 */
package com.codethesis.pgnparse;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.black.knight.chess.domain.Move;

/**
 *
 * @author Deyan Rizov
 *
 */
public class PGNGame {

	private Map<String, String> tags;

	private List<PGNMove> moves;
	
	private String pgn;
	
	public void setPgn(String pgn) {
		this.pgn = pgn;
	}

	PGNGame() {
		tags = new LinkedHashMap<String, String>();
		moves = new LinkedList<PGNMove>();
	}
	
	public PGNGame(String pgn) {
		this();
		this.pgn = pgn;
	}
	
	@Override
	public String toString() {
		return pgn == null ? "" : pgn;
	}

	void addTag(String key, String value) {
		tags.put(key, value);
	}
	
	void removeTag(String key) {
		tags.remove(key);
	}
	
	void addMove(PGNMove move) {
		moves.add(move);
	}
	
	void removeMove(PGNMove move) {
		moves.remove(move);
	}
	
	void removeMove(int index) {
		moves.remove(index);
	}
	
	public String getTag(String key) {
		return tags.get(key);
	}
	
	public Iterator<String> getTagKeysIterator() {
		return tags.keySet().iterator();
	}
	
	public boolean containsTagKey(String key) {
		return tags.containsKey(key);
	}
	
	public int getTagsCount() {
		return tags.size();
	}
	
	public PGNMove getMove(int index) {
		return moves.get(index);
	}
	
	public Iterator<PGNMove> getMovesIterator() {
		return moves.iterator();
	}
	
	public int getMovesCount() {
		return moves.size();
	}
	
	public int getMovePairsCount() {
		return moves.size() / 2;
	}
	
	public ArrayList<Move> toMoves() {
		ArrayList<Move> moves = new ArrayList<Move>();
		
		Iterator<PGNMove> pgnMoves = getMovesIterator();
		
		while(pgnMoves.hasNext()) {
			PGNMove pgnMove = pgnMoves.next();
			
			moves.add(pgnMove.getMyMove());
		}
		
		return moves;
	}
	
	public Map<String, String> getTags() {
		return tags;
	}

	public void setTags(Map<String, String> tags) {
		this.tags = tags;
	}
	
	public boolean isEndGameMarked() {
		for (int i = 0; i < moves.size(); i++) {
			if(moves.get(i).isEndGameMarked() || moves.get(i).isCheckMated()) return true;
		}
		
		return false;
	}
}
